<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    :title="isEdit ? '编辑商品' : '新增商品'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物品类型" prop="category">
            <el-select
              disabled
              v-model="formData.category"
              placeholder="请选择物品类型"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="category in categoryOptions"
                :key="category.key"
                :label="category.desc"
                :value="category.key"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货币类型" prop="platformCurrencyType">
            <el-select
              disabled
              v-model="formData.platformCurrencyType"
              placeholder="请选择货币类型"
              clearable
              style="width: 100%"
            >
              <el-option key="COIN" label="金币" value="COIN" />
              <!-- <el-option key="DIAMOND" label="钻石" value="DIAMOND" /> -->
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="物品ID" prop="goodsId">
            <el-input
              v-model="formData.goodsId"
              placeholder="请输入物品ID"
              style="width: 550px"
              @blur="handleValidateGood"
              @input="handleInputGoodsInfo"
              clearable
            />

            <el-button
              type="primary"
              size="medium"
              style="margin-left: 8px"
              @click="handleValidateGood"
            >
              校验
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="validating-row">
        <!-- <div v-if="userValidationError" class="validation-error">
          {{ userValidationError }}
        </div> -->
        <div v-if="goodsValidating" class="validating-text">
          正在校验用户信息...
        </div>
        <!-- 重新输入时，清空商品信息 -->

        <div
          v-if="!goodsValidating && formData.goods"
          class="goods-info-display"
        >
          <el-avatar :size="40" :src="formData.goods.previewImageUrl">
            <el-icon><User /></el-icon>
          </el-avatar>
          <div class="user-details">
            <div class="user-name">{{ formData.goods.name.zh }}</div>
            <div class="user-id">ID: {{ formData.goodsId }}</div>
          </div>
        </div>
      </div>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="上架状态" prop="enable">
            <el-switch
              v-model="formData.enable"
              active-text="已上架"
              inactive-text="未上架"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">设置价格</el-divider>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="售价" prop="salePrice">
            <el-input
              v-model="formData.salePrice"
              placeholder="请输入售价"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单价" prop="unitPrice">
            <el-input
              v-model="formData.unitPrice"
              placeholder="请输入单价"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="有效期(天数)" prop="durationOfDay">
            <el-input
              v-model="formData.durationOfDay"
              placeholder="请输入有效天数"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">其他配置</el-divider>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  getGoodCategoriesApi,
  type PruductDto,
  type GoodsCategoryRecord,
  checkGoodIdApi,
  addProductApi,
  updateProductApi,
} from "@/api/good";

interface Props {
  modelValue: boolean;
  goodData?: PruductDto | null;
  isEdit?: boolean;
}

interface Emits {
  (e: "update:modelValue", value: boolean): void;
  (e: "submit"): void;
}

const props = withDefaults(defineProps<Props>(), {
  goodData: null,
  isEdit: false,
});

const emit = defineEmits<Emits>();

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const goodsValidating = ref(false);

const formRef = ref<FormInstance>();
const categoryOptions = ref<GoodsCategoryRecord[]>([]);

// 表单数据
const formData = reactive<PruductDto>({
  goodsId: "",
  durationOfDay: null,
  platformCurrencyType: "COIN",
  salePrice: 0,
  unitPrice: 0,
  enable: false,
  remark: "",
  goods: null,
  category: "",
});

// 表单验证规则
const formRules: FormRules = {
  id: [
    { required: true, message: "请输入物品ID", trigger: "blur" },
    { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" },
  ],
  goodsId: [
    { required: true, message: "请输入物品ID", trigger: "blur" },
    { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" },
  ],
  platformCurrencyType: [
    { required: true, message: "请选择货币类型", trigger: "change" },
  ],
  category: [{ required: true, message: "请选择物品分类", trigger: "change" }],
  durationOfDay: [
    { required: true, message: "请选择有效期", trigger: "change" },
  ],
  salePrice: [{ required: true, message: "请输入售价", trigger: "blur" }],
  unitPrice: [{ required: true, message: "请输入单价", trigger: "blur" }],
};

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      loadCategories();
      if (props.isEdit && props.goodData) {
        initFormData();
      } else {
        resetFormData();
      }
    }
  }
);

// 监听 visible 变化
watch(visible, (newVal) => {
  emit("update:modelValue", newVal);
});

// 加载物品分类
const loadCategories = async () => {
  try {
    const response = await getGoodCategoriesApi();
    categoryOptions.value = response.data;
    console.log("物品分类:", response.data);
  } catch (error) {
    console.error("加载物品分类失败:", error);
  }
};

// 初始化表单数据（编辑模式）
const initFormData = () => {
  if (!props.goodData) return;
  // TODO: //

  Object.assign(formData, {
    id: props.goodData.id,
    goodsId: props.goodData.goodsId,
    durationOfDay: props.goodData.durationOfDay,
    platformCurrencyType: props.goodData.platformCurrencyType,
    salePrice: props.goodData.salePrice,
    unitPrice: props.goodData.unitPrice,
    enable: props.goodData.enable,
    remark: props.goodData.remark,
    goods: { ...props.goodData.goods },
    category: props.goodData.category,
  });
};

// 重置表单数据（新增模式）
const resetFormData = () => {
  Object.assign(formData, {
    id: "",
    goodsId: "",
    durationOfDay: null,
    platformCurrencyType: "COIN",
    salePrice: 0,
    unitPrice: 0,
    enable: false,
    remark: "",
    goods: null,
    category: "",
  });
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
  formRef.value?.resetFields();
  resetFormData();
};

const handleInputGoodsInfo = () => {
  formData.goods = null;
  formData.category = "";
  goodsValidating.value = true;

  if (formData.goodsId?.trim() == "") {
    // handleValidateGood();
    goodsValidating.value = false;
  }
};

// 校验主播ID
const handleValidateGood = async () => {
  if (!formData.goodsId) {
    // userValidationError.value = "请输入主播ID";
    return;
  }
  goodsValidating.value = true;
  //   userValidationError.value = "";
  //   userValidationSuccess.value = false;
  //   userInfo.value = null;
  try {
    const response = await checkGoodIdApi(formData.goodsId);
    if (response.code === 200 && response.data) {
      formData.goods = response.data;
      goodsValidating.value = false;
      // 回显物品分类
      formData.category = response.data.category;
      //   userValidationError.value = "";
    } else {
      //   userValidationError.value = "用户不存在";
      goodsValidating.value = false;
    }
  } catch (error) {
    // console.error("校验用户失败:", error);
    // userValidationError.value = "校验失败，请重试";
    goodsValidating.value = false;
  } finally {
    goodsValidating.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    loading.value = true;

    // 更新 name.text 字段
    // formData.name.text =
    //   formData.name.zh || formData.name.en || formData.name.ar;

    // 如果是编辑模式，需要包含ID
    const submitData = props.isEdit
      ? { ...formData, id: props.goodData?.id }
      : formData;
    if (props.isEdit) {
      await updateProductApi(submitData);
    } else {
      // 使用对象解构删除id字段
      const { id, ...dataWithoutId } = submitData;
      console.log("dataWithoutId", dataWithoutId);

      await addProductApi(dataWithoutId);
    }

    ElMessage.success(props.isEdit ? "更新成功" : "创建成功");
    emit("submit");
    handleClose();
  } catch (error) {
    if (error === false) {
      // 表单验证失败
      return;
    }
    console.error("提交失败:", error);
    ElMessage.error(props.isEdit ? "更新失败" : "创建失败");
  } finally {
    loading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  open: () => {
    visible.value = true;
  },
  close: handleClose,
});
</script>

<style scoped lang="less">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.image-preview {
  margin-top: 10px;

  .preview-avatar {
    border: 1px solid #e4e7ed;
    cursor: pointer;
    transition: transform 0.3s;

    &:hover {
      transform: scale(1.1);
    }
  }
}

.upload {
  margin-bottom: 10px;
}

.validating-row {
  margin-left: 50px;
}

.goods-info-display {
  display: flex;
  margin-bottom: 10px;
  .user-details {
    margin-left: 10px;
  }
  .user-name {
    font-size: 16px;
    font-weight: bold;
  }
}

:deep(.el-divider__text) {
  font-weight: bold;
  color: #409eff;
}
</style>
